package cn.usun.httpproxy;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.usun.httpproxy.util.HttpUtils;

/**
 * 
 * ClassName: JavaProxy
 * description: httpproxy servlet implements and cn.usun.httpproxy.web.xml is the use config
 * date: 2016年12月26日 下午1:59:01
 * @author usun
 * @version
 */
public class JavaProxy extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String proxyurl="http://www.baidu.com";

    public JavaProxy() {
    	
    }
    
	public void init(ServletConfig config) throws ServletException {
		String s=config.getInitParameter("proxyurl");
		if(s!=null){
			proxyurl=s;
		}
	}
    
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String _url=request.getRequestURI();
		String queryString = request.getQueryString();
		String strUrl=proxyurl+_url;
		if(queryString!=null&&("".equals(queryString.trim()))==false){
			strUrl+="?"+queryString;
		}
		System.out.println(strUrl);
		ServletOutputStream outputStream = response.getOutputStream();
		
        HttpUtils.getOutputContext(strUrl,outputStream);
        outputStream.close();
	}


	
}
